import { Switch, Input, Select } from 'antd';
import '../index.less';
import React, { useEffect, useState } from 'react'
import { Button } from 'antd';
import { generateUUID } from '@/utils'
import  {stringOperatorOptions,numberOperatorOptions,exetensionOperatorOptions} from '../../../constants'

const FilterOptionsCont = ({ info, editData }) => {

  const FIELD_OPTIONS = [
    { value: 'type', label: '类型' },
    { value: 'size', label: '大小' },
    { value: 'name', label: '名称' },
    { value: 'url', label: '链接' },
    { value: 'extension', label: '扩展名' },
  ];
  
  const TYPE_VALUES = [
    { value: 'image', label: '图片' },
    { value: 'document', label: '文档' },
  ];
  
  const OPERATOR_OPTIONS = {
    type: [
      { value: 'is', label: '是' },
      { value: 'is_not', label: '不是' },
    ],
    size: numberOperatorOptions,
    string: stringOperatorOptions,
    extension: exetensionOperatorOptions,
  };


  const getOperatorOptions = (field) => {
    if (field === 'type') return OPERATOR_OPTIONS.type;
    if (field === 'size') return OPERATOR_OPTIONS.size;
    if (field === 'extension') return OPERATOR_OPTIONS.extension;
    return OPERATOR_OPTIONS.string;
  };

  const renderValueInput = (field, operator, rule) => {
    if (field === 'type') {
      return (
        <Select
          value={rule.value}
          onChange={(value) => {
            editData({
              ...info,
              filter: {
                ...info.filter,
                rules: info.filter.rules.map(r => 
                  r.id === rule.id ? { ...r, value } : r
                )
              }
            });
          }}
          style={{ flex: 1 }}
          options={TYPE_VALUES}
        />
      );
    }
    
    if (field === 'size') {
      return (
        <Input
          type="number"
          placeholder="输入数值"
          value={rule.value}
          onChange={(e) => {
            editData({
              ...info,
              filter: {
                ...info.filter,
                rules: info.filter.rules.map(r => 
                  r.id === rule.id ? { ...r, value: e.target.value } : r
                )
              }
            });
          }}
          style={{ flex: 1 }}
        />
      );
    }

    if (['isEmpty', 'isNotEmpty'].includes(operator)) {
      return null;
    }

    return (
      <Input 
        placeholder="输入值"
        value={rule.value}
        onChange={(e) => {
          editData({
            ...info,
            filter: {
              ...info.filter,
              rules: info.filter.rules.map(r => 
                r.id === rule.id ? { ...r, value: e.target.value } : r
              )
            }
          });
        }}
        style={{ flex: 1 }}
      />
    );
  };

  const renderSection = (title, enabled, onSwitch, children) => (
    <div className={`${title != '排序' ? 'mb-4': ''} ${title != '过滤条件' ? 'mt-6': ''}`}>
      <div className={`flex items-center justify-between ${title != '排序' ? 'mb-2': ''}`} key={title}>
        <span className="text-sm font-bold">{title}</span>
        <Switch
          size="small"
          checked={enabled}
          onChange={onSwitch}
        />
      </div>
      {enabled && children}
    </div>
  );

  const addNewRule = () => {
    const newRule = {
      id: generateUUID(8),
      field: '',
      operator: '',
      value: ''
    };
    editData({
      ...info,
      filter: {
        ...info.filter,
        rules: [...info.filter.rules, newRule]
      }
    });
  };

  const updateRule = (ruleId, field, value) => {
    editData({
      ...info,
      filter: {
        ...info.filter,
        rules: info.filter.rules.map(rule => 
          rule.id === ruleId ? { ...rule, [field]: value } : rule
        )
      }
    });
  };

  const removeRule = (ruleId) => {
    editData({
      ...info,
      filter: {
        ...info.filter,
        rules: info.filter.rules.filter(rule => rule.id !== ruleId)
      }
    });
  };

  return (
    <div className="px-[5px] pt-[2px]">
      {renderSection(
        "过滤条件",
        info.filter?.enabled,
        (checked) => editData({
          ...info,
          filter: {
            ...info.filter,
            enabled: checked
          }
        }),
        <div className="flex flex-col gap-2">
          <div className="flex gap-2">
            <div className="w-[80px] flex">
              <div className="h-[calc(100%-42px)] flex items-center">
                <Button
                  type="default"
                  size="small"
                  className="flex items-center justify-center gap-1 bg-blue-50 border-blue-100 w-full"
                  onClick={() => editData({
                    ...info,
                    filter: {
                      ...info.filter,
                      logic: info.filter?.logic === 'and' ? 'or' : 'and'
                    }
                  })}
                >
                  <span className="w-[32px] text-center">{info.filter?.logic === 'and' ? 'AND' : 'OR'}</span>
                  <svg viewBox="0 0 1024 1024" width="14" height="14" fill="currentColor">
                    <path d="M512 64a448 448 0 1 1 0 896 448 448 0 0 1 0-896zm0 832a384 384 0 1 0 0-768 384 384 0 0 0 0 768zm144.3-228.7L546.1 557.1V384h-68.3v215.9l143.5 143.5 34.7-34.8z"/>
                  </svg>
                </Button>
              </div>
            </div>
            <div className="flex-1 relative">
              <div className="relative pl-3">
                <div className="absolute -left-2 top-[10px] bottom-[10px] w-[6px] border-l-[1px] border-gray-400"></div>
                <div className="absolute -left-2 top-0 w-[6px] h-[10px] border-t-2 border-l-[1px] border-gray-400 rounded-tl"></div>
                <div className="absolute -left-2 bottom-0 w-[6px] h-[10px] border-b-2 border-l-[1px] border-gray-400 rounded-bl"></div>
                {info.filter?.rules.map((rule, index) => (
                  <div key={rule.id} className="flex flex-col gap-2 p-2 border border-gray-200 rounded mb-2">
                    <div className="flex items-center justify-between">
                      <span className="text-sm">条件 {index + 1}</span>
                      <Button 
                        type="text" 
                        danger 
                        size="small"
                        onClick={() => removeRule(rule.id)}
                        disabled={info.filter.rules.length === 1}
                      >
                        删除
                      </Button>
                    </div>
                    
                    <Select
                      value={rule.field}
                      onChange={(field) => updateRule(rule.id, 'field', field)}
                      placeholder="选择过滤字段"
                      style={{ width: '100%' }}
                      options={FIELD_OPTIONS}
                    />
                    
                    <div className="flex items-center gap-2">
                      <Select
                        value={rule.operator}
                        onChange={(value) => updateRule(rule.id, 'operator', value)}
                        style={{ width: 120 }}
                        options={getOperatorOptions(rule.field)}
                      />
                      {renderValueInput(rule.field, rule.operator, rule)}
                    </div>
                  </div>
                ))}
              </div>
              <Button 
                block 
                onClick={addNewRule}
                className="mt-2 h-[24px] w-[100px]"
              >
                + 添加条件
              </Button>
            </div>
          </div>
        </div>
      )}

      {renderSection(
        "取第 N 项",
        info.takeN?.enabled,
        (checked) => editData({
          ...info,
          takeN: {
            ...info.takeN,
            enabled: checked
          }
        }),
        <Input
          type="number"
          min={1}
          value={info.takeN?.value}
          onChange={(e) => {
            editData({
              ...info,
              takeN: {
                ...info.takeN,
                value: parseInt(e.target.value)
              }
            });
          }}
          placeholder="输入数字"
        />
      )}

      {renderSection(
        "取前 N 项",
        info.takeTopN?.enabled,
        (checked) => editData({
          ...info,
          takeTopN: {
            ...info.takeTopN,
            enabled: checked
          }
        }),
        <Input
          type="number"
          min={1}
          value={info.takeTopN?.value}
          onChange={(e) => {
            editData({
              ...info,
              takeTopN: {
                ...info.takeTopN,
                value: parseInt(e.target.value)
              }
            });
          }}
          placeholder="输入数字"
        />
      )}

      {renderSection(
        "排序",
        info.sort?.enabled,
        (checked) => editData({
          ...info,
          sort: {
            ...info.sort,
            enabled: checked,
            order: 'asc'
          }
        }),
        <div className="flex gap-2">
          <Select
            value={info.sort?.field}
            onChange={(value) => {
              editData({
                ...info,
                sort: {
                  ...info.sort,
                  field: value
                }
              });
            }}
            placeholder="选择排序字段"
            style={{ width: '100%' }}
            options={FIELD_OPTIONS}
          />
          <Select
            value={info.sort?.order}
            onChange={(value) => {
              editData({
                ...info,
                sort: {
                  ...info.sort,
                  order: value
                }
              });
            }}
            style={{ width: 100 }}
          >
            <Select.Option value="asc">升序</Select.Option>
            <Select.Option value="desc">降序</Select.Option>
          </Select>
        </div>
      )}
    </div>
  );
};

export default React.memo(FilterOptionsCont);